package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecParamServiceImpl extends ServiceImpl<SpecParamMapper, SpecParam> implements SpecParamService {

    @Autowired
    private SpuService spuService;

    @Autowired
    private SpuDetailService spuDetailService;


    //根据规格参数组得id,查询规格参数集合
    @Override
    public List<SpecParamDTO> querySpecParamListByGroupId(Long gid, Long cid, Boolean searching) {
        return SpecParamDTO.convertEntityList(this.query()
                .eq(null != gid, "group_id", gid)
                .eq(null != cid, "category_id", cid)
                .eq(null != searching, "searching", searching)
                .list()
        );
    }


    //根据spuId,查询spu的所有规格参数,值value
    @Override
    public List<SpecParamDTO> querySpuValuesBySpuId(Long spuId, Boolean searching) {

        //根据商品id查询分类cid3
        Long cid3 = spuService.getById(spuId).getCid3();

        //根据商品分类cid3查询商品规格信息
        List<SpecParamDTO> specParamList = SpecParamDTO.convertEntityList(this.query()
                .eq("category_id", cid3)
                .eq(searching!=null,"searching",searching)
                .list());

        //根据商品supId获取规格参数的详细value信息getSpecification()
        SpuDetail spuDetail = spuDetailService.getById(spuId);
        //字符串无法使用，需要转换为json
        String specification = spuDetail.getSpecification();

        //key规格参数的id  value是规格参数的值在Specification字段中
        Map<Long, Object> valueMap = JsonUtils.nativeRead(specification, new TypeReference<Map<Long, Object>>() {
        });

        //遍历商品规格信息集合,将Value值放入规格参数详细中
        specParamList
                .forEach(specParamDTO -> specParamDTO.setValue(valueMap.get(specParamDTO.getId())));

        return specParamList;
    }

    //新增规格参数
    @Override
    @Transactional
    public void addSpecParam(SpecParamDTO specParamDTO) {
        if (specParamDTO != null) {
            this.save(specParamDTO.toEntity(SpecParam.class));
        }
    }


    //修改规格参数
    @Override
    @Transactional
    public void updateSpecParam(SpecParamDTO specParamDTO) {
        if (specParamDTO != null) {
            this.updateById(specParamDTO.toEntity(SpecParam.class));
        }
    }
}
